package com.warmheart.base.filter;

import java.io.IOException;
import java.util.Date;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.warmheart.base.executor.TraceContext;

public class CustomInitFilter implements Filter {

    private static Logger logger = LoggerFactory.getLogger(CustomInitFilter.class);

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
            ServletException {
        Date startTime = new Date();
        TraceContext.init();
        logger.info("----------------------------请求开始----------------------------");
        try {
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            if (request instanceof HttpServletRequest) {
                HttpServletRequest hRequest = (HttpServletRequest) request;
                logger.info("请求路径：" + hRequest.getRequestURI());
                chain.doFilter(hRequest, response);
            } else {
                chain.doFilter(request, response);
            }
        } catch (Exception e) {
            // 由于下级异常已被层层捕获，这里不再处理异常，打印日志记录即可（理论上不存在）
            logger.error("自定义初始化过滤器异常：" + e.getMessage(), e);
        } finally {
            Long nextSpanCost = TraceContext.getSpanCost();
            Date endTime = new Date();
            Long currSpanCost = endTime.getTime() - startTime.getTime() - nextSpanCost;
            logger.info("自定义初始化耗时{}ms", currSpanCost);
            logger.info("请求总耗时{}ms", endTime.getTime() - startTime.getTime());
            logger.info("----------------------------请求结束----------------------------");
            TraceContext.clear();
        }
    }
}
